// components/Sidebar.tsx
import pathIcon from '@/assets/path.png';

import { projectAdd } from '@/services/workBench';
import { useStoreWorkbench } from '@/store/workbench';
import { Layout, Menu } from 'antd';
import { useEffect, useState } from 'react';

import { PlusOutlined } from '@ant-design/icons';
import AddModal from './AddModal';
import styles from './index.less';

const { Sider } = Layout;

interface Iprops {
  projectData: any[];
}

const Sidebar = (props: Iprops) => {
  const { projectData } = props;
  const { updateAnyValue } = useStoreWorkbench();
  const [collapsed, setCollapsed] = useState(false);
  const [visibleModal, setVisibleModal] = useState(false);
  const [selectedKey, setSelectedKey] = useState('require-未分类会话');
  const [projectList, setProjectList] = useState<any[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);

  useEffect(() => {
    if (selectedKey) {
      const projectIdBro = openKeys?.[0]?.split('-')[1] || null;
      // eslint-disable-next-line
      const item = projectList.find((item: any) => item.id == projectIdBro);
      // 1、如果点的是需求--openkeys必然存的项目id
      if (selectedKey.includes('require-')) {
        updateAnyValue({
          currentMenuItem: {
            ...item,
            projectId: openKeys?.[0]?.split('-')[1] || null,
            requireId: selectedKey?.split('-')[1] || null,
            menuType: '需求',
          },
        });
      } else {
        // 2、如果点的是项目--openkeys必然存的是项目id
        updateAnyValue({
          currentMenuItem: {
            ...item,
            projectId: openKeys?.[0]?.split('-')[1] || '',
            requireId: null,
            menuType: '项目',
          },
        });
      }
    }
  }, [selectedKey]);

  const toggleSidebar = () => {
    setCollapsed(!collapsed);
  };

  // 点击单个项目或者需求
  const handleClick = async (info: any) => {
    if (info?.key?.includes('未分类会话')) {
      setSelectedKey(info.key);
      setOpenKeys([]);
      return;
    }
    if (info.item.props?.hasOwnProperty('requirementList')) {
      setSelectedKey(info.key);
      setOpenKeys([info.key]);
    } else {
      setSelectedKey(info.key);
    }
  };

  // 点击单个需求的项目
  const handleOpenChange = async (keys: any) => {
    if (keys && keys.length === 1) {
      setOpenKeys(keys);
      setSelectedKey(keys?.[0] || '');
    }
    if (keys && keys.length === 2) {
      // openKeys
      const arr = keys.filter((item: string) => {
        return !openKeys.includes(item);
      });
      setOpenKeys(arr);
      setSelectedKey(arr?.[0] || '');
    }
  };

  // 新增项目
  const handleAdd = async (values: any) => {
    await projectAdd(values);
  };

  const handleMenus = (menusData: any[]) => {
    const loop = (list: any[]): any[] => {
      if (!Array.isArray(list)) return [];
      return list.map((ele: any): any => {
        return {
          ...ele,
          key: ele.hasOwnProperty('requirementList')
            ? 'project-' + ele?.id
            : 'require-' + ele?.id,
          // icon: <img className={styles.icon} src={cjglIcon} />,
          // selectIcon: <img className={styles.icon} src={cjglSelectIcon} />,
          label: ele?.name ? ele?.name : ele?.title,
          id: ele?.id,
          children:
            ele.requirementList?.length > 0 ? loop(ele.requirementList) : null,
        };
      });
    };
    const res = loop(menusData);
    if (res.length) {
      return res;
    }
    return [];
  };

  useEffect(() => {
    if (projectData.length > 0) {
      // 处理一下项目--菜单
      const newList = handleMenus(projectData);
      setProjectList(newList);
      updateAnyValue({
        menusList: newList,
      });
    }
  }, [projectData]);

  return (
    <div className={styles.sidebar} style={{ width: collapsed ? 0 : 220 }}>
      <div className={styles.content}>
        <div className={styles.title}>my workspace</div>
        <PlusOutlined
          className={styles.addIcon}
          onClick={() => {
            setVisibleModal(true);
            setTimeout(() => {
              setVisibleModal(false);
            });
          }}
        />
        <Sider
          width={200}
          theme="light"
          collapsed={collapsed}
          collapsedWidth={0}
        >
          <Menu
            openKeys={openKeys}
            onOpenChange={handleOpenChange}
            onClick={handleClick}
            mode="inline"
            selectedKeys={[selectedKey]}
            style={{ height: '100%', borderRight: 0 }}
            items={projectList}
            // inlineCollapsed={collapsed}
          />
        </Sider>
      </div>
      {/* 切换按钮 */}
      <img
        src={pathIcon}
        className={`${styles.iconImg} ${!collapsed ? styles.iconShifted : ''}`}
        onClick={toggleSidebar}
      />

      <AddModal visibleModal={visibleModal} onGenerate={handleAdd} />
    </div>
  );
};

export default Sidebar;
